<template>
	<view class="body">
		<img :src="bgImgSrc" class="bgImg" alt="" />
		<img :src="headerImgSrc" class="HeaderImg" alt="" />
		<view class="box">
			<view v-for="(item,index) in prize_arr" :key="item.id">
				<!-- 判断是奖品还是抽奖按钮 -->
				<view v-if="item.type=='btn'" @click="clickPrize" class="prize btn" :class="isTurnOver?'':'grayscale'">
					{{item.name}}
				</view>
				<view v-else class="prize" :class=" item.isSelected? 'selected':''">
					<image class="prize-img" :src="item.goodImage" mode="aspectFill" style="opacity:0.8;"></image>
					<!-- {{item.name}} -->
				</view>
			</view>
		</view>
		<view class="text-box" scroll-y="true">
			<text>活动最终解释权归平台所有</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userdata: {
					openId: '',
					token: ''
				},
				activityId: '',
				prize_goodId:'',
				prize_data:'',
				prize_arr: [{
						id: '1',
						type: 'prize',
						name: '奖品1',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '2',
						type: 'prize',
						name: '奖品2',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '3',
						type: 'prize',
						name: '奖品3',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '8',
						type: 'prize',
						name: '奖品8',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '999',
						type: 'btn',
						name: '抽奖',
						goodImage: '',
						goodId: '',
						isSelected: false
					},
					{
						id: '4',
						type: 'prize',
						name: '奖品4',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '7',
						type: 'prize',
						name: '奖品7',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '6',
						type: 'prize',
						name: '奖品6',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
					{
						id: '5',
						type: 'prize',
						name: '奖品5',
						goodImage: '../../static/lottery/th.jpg',
						goodId: '',
						isSelected: false
					},
				],
				// 抽奖状态，是否转完了
				isTurnOver: true,
				isfinish:false,
				isgetPrize:false,
				bgImgSrc: require('../../static/lottery/bg.png'),
				headerImgSrc: require('../../static/lottery/header.png')
			}
		},
		methods: {
			async getPrizeByActId() {
				await this.$myRequest({
					url: '/organizer/getPrizeByActivityId',
					method: 'GET',
					header: {
						Authorization: this.userdata.token,
						'content-type': 'application/x-www-form-urlencoded',
					},
					data: {
						activityId: this.activityId
					},
				}).then(res => {
					console.log(res)
					this.prize_data=res.data.data
					let data = res.data.data
					for (let i = 0, j = 0; j < data.length; i++) {
						if (i == 4) {
							continue
						}
						this.prize_arr[i].activityId = data[j].activityId
						this.prize_arr[i].businessId = data[j].businessId
						this.prize_arr[i].goodId = data[j].goodId
						this.prize_arr[i].goodImage = data[j].goodImage
						this.prize_arr[i].goodName = data[j].goodName
						j++;
					}
					console.log(this.prize_arr, 'prize_arr');
				}).catch(err => {
					console.log(err)
				})

			},
			//获取抽奖中奖id
			getPrizeDrawId() {
				return new Promise((resolve, reject) => {
					this.$myRequest({
						url: '/user/lotteryDraw',
						method: 'POST',
						header: {
							Authorization: this.userdata.token,
							'content-type': 'application/x-www-form-urlencoded',
						},
						data: {
							openId: this.userdata.openId,
							activityId: this.activityId
						},
					}).then(res => {
						console.log(res.data.data, '获奖奖品');
						this.prize_goodId=res.data.data
						if(this.prize_goodId==-1){
							this.isgetPrize=false
							resolve(this.prize_data.length)
						}
						// let prizeIdx = this.prize_arr.findIndex((item) => item.goodId === res.data.data)
						else{
							this.isgetPrize=true
							let prizeIdx = this.prize_arr.find((item) => item.goodId === res.data.data).id
							resolve(prizeIdx)
						}
						// if(prizeIdx<3)
						// 	resolve(prizeIdx + 1)
						// else
						// 	resolve(prizeIdx)
					}).catch(err => {
						console.log(err)
					})
				})
			},
			async clickPrize() {
				if(this.isfinish&&this.isgetPrize){
					uni.showModal({
						title: '提示',
						content: '恭喜中奖！',
						cancelText: "取消", // 取消按钮的文字  
						confirmText: "填写订单", // 确认按钮的文字  
						showCancel: true, // 是否显示取消按钮，默认为 true
						confirmColor: '#f55850',
						cancelColor: '#39B54A',
						success: (res) => {
							if (res.confirm) {
								// console.log('comfirm') //点击确定
								uni.navigateTo({
									url: '/pages/myorder-submit/myorder-submit?goodId='+this.prize_goodId+'&activityId='+this.activityId,
									success: res => {},
									fail: () => {},
									complete: () => {}
								});
							} else {
								console.log('cancel') //点击取消
							}
						}
					})
				}
				else if(this.isfinish&&!this.isgetPrize){
					uni.showToast({
						title: '您的手气不好，再看看其他活动吧',
						icon: 'none'
					})
				}
				if(!this.isfinish){
					if (this.isTurnOver) {
						this.isTurnOver = false;
						let prize_id = await this.getPrizeDrawId()
						console.log(prize_id, 'prize_id');
						//假设为7 @TODO
						// let prize_id = 8;
						// 调用抽奖方法
						this.lottery(prize_id);
					} else {
						uni.showToast({
							title: '请勿重复点击',
							icon: 'none'
						})
					}
				}

			},

			// 抽奖旋转动画方法
			lottery(prize_id) {
				console.log('中奖ID：' + prize_id)
				/*
				 * 数组的长度就是最多所转的圈数，最后一圈会转到中奖后的位置
				 * 数组里面的数字表示从一个奖品跳到另一个奖品所需要的时间
				 * 数字越小速度越快
				 * 想要修改圈数和速度的，更改数组个数和大小即可
				 */
				let num_interval_arr = [90, 80, 70, 60, 50, 50, 50, 100, 150, 250];
				// 旋转的总次数
				let sum_rotate = num_interval_arr.length;
				// 每一圈所需要的时间
				let interval = 0;
				num_interval_arr.forEach((delay, index) => {
					setTimeout(() => {
						this.rotateCircle(delay, index + 1, sum_rotate, prize_id);
					}, interval)
					//因为每一圈转完所用的时间是不一样的，所以要做一个叠加操作
					interval += delay * 8;
				})
			},

			rotateCircle(delay, index, sum_rotate, prize_id) {
				// console.log(index)
				let _this = this;
				/*
				 * 页面中奖项的实际数组下标
				 * 0  1  2
				 * 3     5
				 * 6  7  8
				 * 所以得出转圈的执行顺序数组为 ↓
				 */
				let order_arr = [0, 1, 2, 5, 8, 7, 6, 3];
				// 页面奖品总数组
				let prize_arr = this.prize_arr;
				// 如果转到最后以前，把数组截取到奖品项的位置
				if (index == sum_rotate) {
					order_arr.splice(prize_id)
				}
				for (let i = 0; i < order_arr.length; i++) {
					setTimeout(() => {
						// 清理掉选中的状态
						prize_arr.forEach(e => {
							e.isSelected = false
						})
						// 执行到第几个就改变它的选中状态
						prize_arr[order_arr[i]].isSelected = true;
						// 更新状态
						_this.prize_arr = prize_arr
						// 如果转到最后一圈且转完了，把抽奖状态改为已经转完了
						if (index == sum_rotate && i == order_arr.length - 1) {
							_this.isTurnOver = true
							_this.isfinish=true
							setTimeout(()=>{
								if(this.isgetPrize){
									uni.showModal({
										title: '提示',
										content: '恭喜中奖！',
										cancelText: "取消", // 取消按钮的文字  
										confirmText: "填写订单", // 确认按钮的文字  
										showCancel: true, // 是否显示取消按钮，默认为 true
										confirmColor: '#f55850',
										cancelColor: '#39B54A',
										success: (res) => {
											if (res.confirm) {
												// console.log('comfirm') //点击确定
												uni.navigateTo({
													url: '/pages/myorder-submit/myorder-submit?goodId='+this.prize_goodId+'&activityId='+this.activityId,
													success: res => {},
													fail: () => {},
													complete: () => {}
												});
											} else {
												console.log('cancel') //点击取消
											}
										}
									})
								}
								else{
									uni.showToast({
										title: '您的手气不好，再看看其他活动吧',
										icon: 'none'
									})
								}

							},1200)
						}
					}, delay * i)
				}



			},

			async getStorage() {
				const openId = uni.getStorageSync('openId')
				const token = uni.getStorageSync('token')
				this.userdata.openId = openId
				this.userdata.token = token
				console.log(this.userdata.token, 'token');
			},
		},
		beforeCreate(options) {
			console.log(options, 'beforeCreate');
		},
		onLoad(options) {
			this.getStorage()
			console.log(options, 'onload')
			this.activityId = options.activityId
			this.getPrizeByActId(this.activityId)
		},
		onShow() {
			console.log('onshow');
		}
	}
</script>

<style>
	.body {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100vw;
		height: 100vh;
	}

	.box {
		display: flex;
		flex-wrap: wrap;
		width: 600rpx;
	}

	.box .prize {
		width: 190rpx;
		height: 190rpx;
		line-height: 200rpx;
		text-align: center;
		font-size: 40rpx;
		font-weight: 700;
		color: white;
		background-color: white;
		z-index: -1;
		border: 2px solid snow;
		margin: 2px;
		box-sizing: border-box;
	}

	.box .prize .prize-img {
		width: 100%;
		height: 100%;
		z-index: 2;
	}

	.box .btn {
		color: tomato;
		background-color: gold;
		/* border-radius: 50%; */
	}

	.box .selected {
		background-color: orangered;
	}

	.grayscale {
		filter: grayscale(50%);
	}

	.text-box {
		position: absolute;
		bottom: 5%;
		font-size: small;
		color: #CDCDCD;
	}

	.bgImg {
		position: absolute;
		background-position: center center;
		width: 100%;
		height: 100%;
		z-index: -1;
	}

	.HeaderImg {
		/* position: absolute; */
		width: 300px;
		height: 170px;
		left: 50%;
	}
</style>